package com.live.task;

import java.util.List;
import java.util.Map;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.live.activity.R;
import com.live.common.Constant;
import com.live.tools.LiveTools;

public class LiveScoreCache extends AsyncTask<Bundle, Integer, String> {

	private List<Map<String, Object>> liveScoreList = null;

	private ListView scoreList;

	private Context context = null;

	private String matchId = null;

	private TextView homeTeamScore = null;

	private TextView visitTeamScore = null;

	private TextView matchStatus = null;

	public LiveScoreCache(Context context, ListView scoreList, TextView homeTeamScore, TextView visitTeamScore,
			TextView matchStatus) {
		this.context = context;
		this.scoreList = scoreList;
		this.matchStatus = matchStatus;
		this.homeTeamScore = homeTeamScore;
		this.visitTeamScore = visitTeamScore;
	}

	// 此方法在主线程执行,当任务执行之前开始调用此方法，可以在这里显示进度对话框
	@Override
	protected void onPreExecute() {
		super.onPreExecute();
	}

	// 此方法在后台线程执行，完成任务的主要工作，通常需要较长的时间。
	// 在执行过程中可以调用publicProgress(Progress...)来更新任务的进度。

	@Override
	protected String doInBackground(Bundle... params) {
		Log.i("PageTask", "doInBackground... " + Thread.currentThread().getId());

		matchId = params[0].getString("matchId");

		// 读取本机缓存数据
		liveScoreList = LiveTools.readFile(context, "score_" + matchId + ".xml".toString());
		if (liveScoreList.size() > 0) {
			publishProgress();
		}
		return null;
	}

	// 此方法在主线程执行，用于显示任务执行的进度
	@Override
	protected void onProgressUpdate(Integer... values) {
		super.onProgressUpdate(values);
		Log.i("PageTask", "onProgressUpdate()  " + Thread.currentThread().getId());

		SimpleAdapter adapter = new SimpleAdapter(context, liveScoreList, R.layout.score_list, new String[] {
				"scoreTime", "homeTeamScore", "visitTeamScore", "scoreAction" }, new int[] { R.id.scoreTime,
				R.id.homeTeamScore, R.id.visitTeamScore, R.id.scoreAction });

		scoreList.setAdapter(adapter);

		Map<String, Object> score = liveScoreList.get(0);

		// 更新比分
		if (score.get("homeTeamScore") != null) {
			homeTeamScore.setText((String) score.get("homeTeamScore"));
		}
		if (score.get("visitTeamScore") != null) {
			visitTeamScore.setText((String) score.get("visitTeamScore"));
		}

		// 更新状态
		if (Constant.MATCH_STATUS_1.equals(matchStatus.getText().toString())) {
			matchStatus.setText(Constant.MATCH_STATUS_2);
		}

	}

	// 此方法在主线程执行，任务执行的结果作为此方法的参数返回。
	@Override
	protected void onPostExecute(String result) {
		Log.i("PageTask", "onPostExecute()  " + Thread.currentThread().getId());
	}
}